package com.cloud.logger.zchain.zchainserver.service;

import com.cloud.logger.zchain.core.common.util.DateUtil;
import com.cloud.logger.zchain.zchainserver.entity.*;
import com.cloud.logger.zchain.zchainserver.entity.propertyenum.SwitchEnum;
import com.cloud.logger.zchain.zchainserver.mail.MailInfo;
import com.cloud.logger.zchain.zchainserver.mail.MailService;
import com.cloud.logger.zchain.zchainserver.mongo.*;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.Date;
import java.util.List;

import static java.util.stream.Collectors.joining;

/**
 * @Author: wcy
 * @Description:
 * @Date: Created in 2017/12/13 11:47
 * @Modified By:
 */
@Service
public class CheckProjectService {

    @Resource
    private AngelaProjectRepository angelaProjectRepository;
    @Resource
    AngelaProjectNodeRepository angelaProjectNodeRepository;
    @Resource
    AngelaProjectNodeDetailRepository nodeDetailRepository;
    @Resource
    MailService mailService;
    @Resource
    ProjectUserRelationRepository projectUserRelationRepository;
    @Resource
    ZchianUserRepository zchianUserRepository;

    //绑定邮箱模板
    static String mess = "<div id=\"qm_con_body\"><div id=\"mailContentContainer\" class=\"qmbox qm_con_body_content qqmail_webmail_only\" style=\"\"><div style=\"background-color:#d0d0d0;background-image:url(http://weixin.qq.com/zh_CN/htmledition/images/weixin/letter/mmsgletter_2_bg.png);text-align:center;padding:40px\"><div class=\"mmsgLetter\" style=\"width:680px;margin:0 auto;padding:10px;color:#333;background-color:#fff;border:0 solid #aaa;border-radius:5px;-webkit-box-shadow:3px 3px 10px #999;-moz-box-shadow:3px 3px 10px #999;box-shadow:3px 3px 10px #999;font-family:Verdana,sans-serif\"><div class=\"mmsgLetterHeader\" style=\"height:23px;background:url(http://weixin.qq.com/zh_CN/htmledition/images/weixin/letter/mmsgletter_2_bg_topline.png)repeat-x 0 0\"></div><div class=\"mmsgLetterContent\" style=\"text-align:left;padding:30px;font-size:14px;line-height:1.5\"><div><p class=\"salutation\" style=\"font-weight:bold\"><span id=\"mailUserName\">尊敬的各位管理人</span>：</p><div style=\"margin-top:36px\"><table border=\"1\" align=\"center\" rules=\"all\" cellpadding=\"10\" style=\"text-align:center\"><tr><td colspan=\"6\"><h4 style=\"margin:0\">项目关闭通知</h4></td></tr><tr style=\"background:#F2FAFF\"><td>客户</td><td>项目名</td><td>ip</td><td>port</td><td>情况</td></tr><tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>已关闭：{4}分钟</td></tr></table></div></div></div></div></div></div></div>";


    private static PropertiesConfiguration config;

    static{
        try {
            config = new PropertiesConfiguration("mail.properties");
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
    }

    public CheckProjectService() throws ConfigurationException {
    }

    public void checkProject(){
        List<AngelaLoggerProjectNode> nodeList = angelaProjectNodeRepository.findAll();
        for(AngelaLoggerProjectNode node:nodeList){
            //如果获取到createTime并状态开启(两边状态相同不更新，不同则更新数据)
            if(SwitchEnum.off.equals(node.getStatus())){
                AngelaLoggerProjectNodeDetail detail = nodeDetailRepository.findFirstByCodeAndIpAndPortAndCreateTimeAfterOrderByCreateTimeDesc(
                        node.getCode()
                        ,node.getIp(),node.getPort(), DateUtil.addMinute(new Date(),-10));
                if(detail!=null && (detail.getCreateTime().before(DateUtil.addMinute(new Date(),-5)))){
                    AngelaLoggerProject project = angelaProjectRepository.findOneByCode(node.getCode());
                    if((SwitchEnum.on).equals(project.getMailRemind())&&(SwitchEnum.on).equals(node.getMailForbidden())){
                        List<ProjectUserRelation> projectUserRelations = projectUserRelationRepository.findByProjectId(project.getId());
                        String mails = projectUserRelations.stream().map(projectUserRelation -> getMail(projectUserRelation)).collect(joining(";"));
                        MailInfo info = new MailInfo();
                        info.setFormName(mails);
                        info.setToAddress(mails);
                        info.setSubject("zchain日志服务关闭提醒,请看到邮件的管理员,尽快解决");
                        info.setContent(contentFormat(project,node,detail));
                        mailService.sendHtmlMail(info, node);
                    }
                }

            }
        }
    }

    private String getMail(ProjectUserRelation projectUserRelation){
        ZchainUser user = zchianUserRepository.findOne(projectUserRelation.getUserId());
        return user ==null?"":user.getEmail();
    }

    private String contentFormat(AngelaLoggerProject project, AngelaLoggerProjectNode node, AngelaLoggerProjectNodeDetail detail){

        //获得填充的数据
        Object[] args={project.getName(),project.getName(),node.getIp(),node.getPort(),5};
        //新建标准的格式
        MessageFormat formatter =new MessageFormat("");
        //获得格式转换为中文，防止中文乱码
        //从资源文件中获取相应的模板信息
        formatter.applyPattern(mess);
        //填充模板
        return formatter.format(args);

    }
}
